package com.peanut.mq;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(topic = "phoneNum_Topic",consumerGroup = "phoneNum_consumer")
class SendPhoneMsg implements RocketMQListener<String>,  RocketMQPushConsumerLifecycleListener{
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(String phone) {
        System.out.println(phone);
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                redisTemplate.setKeySerializer(new StringRedisSerializer());
                redisTemplate.setValueSerializer(new StringRedisSerializer());

                //获取手机号
                byte[] body = list.get(0).getBody();
                String phone = new String(body);

                Client client = null;
                try {
                    client = createClient(" LTAI4GCbdwnjCGwQj9Z3tr3N", " 27ih4pc1W1tqey9X4mmCy1JUotAX7L");
                    String code = RandomStringUtils.randomNumeric(4);
                    SendSmsRequest sendSmsRequest = new SendSmsRequest()
                            .setPhoneNumbers(phone)
                            .setSignName("XXXX") //签名
                            .setTemplateCode("SMS_162522027")//模板名
                            .setTemplateParam("{\"sms_code\":\"" + code + "\"}");//模板需要的变量

                    // 复制代码运行请自行打印 API 的返回值
                    client.sendSms(sendSmsRequest);
                    //将手机号验证码放进redis中,并设置过期时间
                    redisTemplate.opsForValue().set(phone,code,30, TimeUnit.MINUTES);
                    //消息消费成功
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                } catch (Exception e) {
                    e.printStackTrace();
                    //消息消费失败,重新消费
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
}
